package com.hs.service.impl;
/*
 * @Author:iWeeper
 * @Date:2022/6/16 20:38
 * @Version:1.0
 * */

import com.hs.mapper.SequenceMapper;
import com.hs.service.SequenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

@Service
public class SequenceServiceImpl implements SequenceService {

    @Autowired
    private SequenceMapper sequenceMapper;

    public  String nextValue(String seqName,Integer roleId){
        //工号、学号
        String num = "";
        try{
            //获取下一个编号
            Integer value = sequenceMapper.nextValue(seqName);
            //获取当前年份
            Calendar cl = Calendar.getInstance();
            int year = cl.get(Calendar.YEAR);
            /*
            根据不同角色生成工号
            1、学生：年份+角色ID+5位的编号
            2、教师：年份+角色ID+3位的编号
            3、管理员：年份+角色ID+2位的编号
             */
            if(roleId==2){
                num = String.valueOf(year)+String.valueOf(roleId)+formatNum(value,3);
            }else if(roleId==3){
                num = String.valueOf(year)+String.valueOf(roleId)+formatNum(value,5);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return num;
        }
    }


    public  String courseCode(String seqName){
        //工号、学号
        String num = "";
        try{
            //获取下一个编号
            Integer value = sequenceMapper.nextValue(seqName);
            //获取当前年份
            Calendar cl = Calendar.getInstance();
            int year = cl.get(Calendar.YEAR);
            num = "EDU"+String.valueOf(year)+formatNum(value,3);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return num;
        }
    }

    public  String formatNum(Integer num,Integer length){
        String result = "";
        //参数不能为空
        if(num!=null&&length!=null){
            String numStr = String.valueOf(num);
            //需要格式化的数值长度不能比格式话的目标长度长，如果比目标长度还长则原样返回
            if(numStr.length()<length){
                //补0
                for(int i=0;i<length-numStr.length();i++){
                    result += "0";
                }
                result += numStr;
            }else{
                result = numStr;
            }
        }
        return result;
    }
}
